// Author: wsfuyibing <682805@qq.com>
// Date: 2025-06-24

package unlock

import (
	"context"
	"gitee.com/go-libs/db-xorm/db"
	"gitee.com/go-libs/log"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/kind"
	"server/app/lib/user_balance/operations"
	"sync"
)

var (
	once     = new(sync.Once)
	operator *Operator
)

// Operator
// 解锁余额.
//
// 解锁(解冻)用户的指定金额, 返回到用户账户中, 可以继续消费.
type Operator struct {
	operations.Operations
}

// New
// 获取单例.
func New() *Operator { return operator }

// Run
// 执行逻辑.
func (o *Operator) Run(ctx context.Context, sess *db.Session, uid kind.UserId, balance kind.Balance, bo kind.BalanceOperate, link kind.Link, params kind.LinkParams) (err error) {
	var latest, record *models.BalanceRecords

	// 1. 开始解冻.
	log.Infofc(ctx, `[lib][balance][user] 开始解冻余额: user-id="%v"`, uid)

	// 2. 监听结束
	defer func() {
		if err != nil {
			log.Warnfc(ctx, `[lib][balance][user] 解冻余额失败: %v`, err)
		} else {
			log.Infofc(ctx, `[lib][balance][user] 解冻余额结束`)
		}
	}()

	// 4. 读取流水.
	if latest, _, err = o.GetLatestRecord(ctx, sess, uid); err != nil {
		return
	}

	// 5. 创建记录.
	record = &models.BalanceRecords{
		UserId:        uid,
		OperateType:   kind.BalanceOperateUnlock,
		OperateIncome: kind.BalanceIncomeYes,
	}

	// 5.1 金额参数.
	record.Before = latest.Balance
	record.Operate = balance
	record.Balance = record.Before + balance

	// 6. 设置余额.
	//    记录用户最后的余额.
	if err = o.SetUserBalance(ctx, sess, uid, record.Balance); err != nil {
		return
	}

	// 7. 计数累加.
	if err = o.SetUserFreezed(ctx, sess, uid, balance.Reverse()); err != nil {
		return
	}

	// 8. 添加流水.
	_, err = services.NewBalanceRecordsService(sess).Dao.AddByStruct(ctx, record)
	return
}

func init() {
	once.Do(func() {
		operator = &Operator{}
	})
}
